# coding=utf-8

import os
import time
import json

from django.conf.urls import url
from django.http import JsonResponse

from apps.mgr.share import app_logger, danger_logger

from apps.mgr.handlers import (
    loginout, grade_subject_textbook_knowledge,
    customtag, exam, question, lesson, qiniucloud,
    school, school_class, teacher, student, schooltype,
    parent, product, stats, operators, goods, yjaccount,
    notice, mgr, identity_authentication, tasks, proxy,
    order, coupon, publisher, exam_book)
from lib.common import LOG_ACTION_CHINESE

Error_Not_Login = JsonResponse({
    'retcode': 302,
    'msg': '未登录',
    'redirect': '/mgr/login/login.html',
})
Error_UserType = JsonResponse({
    'retcode': 1,
    'msg': '请以正确权限的帐号登录',
    'redirect': '/mgr/login/login.html',
})

# A simple security checking, more preventions are needed in risky APIs: modification, deletion, insert etc.
# user type to http referer string
HTTP_REFERER_DICT = {
    1: '/mgr/',
    1001: '/datainputer/',
    1002: '/ragent/',
    1003: '/custom/',
    1004: '/operator/',
    10010: '/temporary/',
    10011: '/shipper/'
}


def CheckUserIsAdminForApiCaller(request, *args, **kwargs):
    # if not request.user.is_authenticated():
    #     return Error_Not_Login
    execStartTime = time.time()

    if 'ut' not in request.session:
        return Error_Not_Login

    if request.session['ut'] not in (1, 1002, 1003, 1004, 10010, 10011):
        return Error_UserType

    referer = request.META.get('HTTP_REFERER')
    if referer and (HTTP_REFERER_DICT[request.session['ut']] in referer):
        pass
    else:
        return Error_UserType

    realCall = kwargs.pop('_viewFunc')

    ret = realCall(request, *args, **kwargs)

    if request.method in ('POST', 'DELETE', 'PUT'):
        url_path = request.path
        action_dict = LOG_ACTION_CHINESE.get(url_path.split('/')[3] if len(url_path.split('/')) > 4 else None)
        if not action_dict:
            danger_logger.info('!! 通知开发人员添加 [{method}] user_id : {user}, path : {path}, data: {data}'.format(method=request.method,
                                                                                               user=request.session.get('_auth_user_id'),
                                                                                               path=url_path,
                                                                                               data=json.dumps(request.param_dict)))
        else:
            if request.method == 'DELETE':
                danger_logger.info('用户id {user} ，操作 {name} 模块，使用 删除 动作。路径 {path} ， 数据 {data} 。'.format(
                    user=request.session.get('_auth_user_id'), name=action_dict['name'],
                    path=url_path, data=json.dumps(request.param_dict)
                ))
            else:
                danger_logger.info('用户id {user} ，操作 {name} 模块，使用 {action} 动作。路径 {path} ， 数据 {data} 。'.format(
                    user=request.session.get('_auth_user_id'), name=action_dict['name'],
                    action=action_dict.get(request.param_dict.get('action'), '未知'),
                    path=url_path, data=json.dumps(request.param_dict)
                ))

    execEndTime = time.time()
    # 所有大于100ms的操作，产生日志告警
    opTime = execEndTime - execStartTime
    if (opTime > 0.1):
        app_logger.warning('!! op takes %s seconds : function:%s %s  ' % (opTime, request.method, request.path))

    return ret


urlpatterns_api = []


def addPreCheck(urlpatterns, checkFunC):
    for pattern in urlpatterns:
        urlRegx = pattern[0]
        if type(urlRegx) != list:
            urlRegList = [urlRegx]
        else:
            urlRegList = urlRegx

        viewFunc = pattern[1]
        if len(pattern) == 2:
            for one in urlRegList:
                urlpatterns_api.append(url(one, checkFunC, {'_viewFunc': viewFunc}))

        elif len(pattern) == 3:
            otherPara = pattern[2]
            otherPara['_viewFunc'] = viewFunc
            for one in urlRegList:
                urlpatterns_api.append(url(one, checkFunC, otherPara))
        else:
            # print '!!unsupported url format : %s' % pattern
            os._exit(3)


urlpatterns_api_agrs = [

    ([ r'^yj_grades/$',
       r'^yj_grades/(?P<resource_id>\w+)/$'],
     grade_subject_textbook_knowledge.grade_handler.dispatch),

    ([r'^yj_subjects/$',
      r'^yj_subjects/(?P<resource_id>\w+)/$',],
     grade_subject_textbook_knowledge.subject_handler.dispatch),

    ([r'^yj_textbookvers/$',
      r'^yj_textbookvers/(?P<resource_id>\w+)/$',],
     grade_subject_textbook_knowledge.textbook_version_handler.dispatch),

    ([r'^yj_textbookvols/$',
      r'^yj_textbookvols/(?P<resource_id>\w+)/$',],
     grade_subject_textbook_knowledge.textbook_volumn_handler.dispatch),

    ([r'^yj_textbookunits/$',
      r'^yj_textbookunits/(?P<resource_id>\w+)/$',],
     grade_subject_textbook_knowledge.textbook_unit_handler.dispatch),

    ([r'^yj_knowledgestruct/$',
      r'^yj_knowledgestruct/(?P<resource_id>\w+)/$',],
     grade_subject_textbook_knowledge.knowledge_struct_handler.dispatch),


    ([r'^yj_questiontags/$',
      r'^yj_questiontags/(?P<resource_id>\w+)/$',],
     customtag.question_tag_handler.dispatch),

    ([r'^yj_examtags/$',
      r'^yj_examtags/(?P<resource_id>\w+)/$',],
     customtag.exam_tag_handler.dispatch),


    ([r'^yj_lessontags/$',
      r'^yj_lessontags/(?P<resource_id>\w+)/$',],
     customtag.lesson_tag_handler.dispatch),

    ([r'^yj_questions/$',
      r'^yj_questions/(?P<question_type>\w+)/$',
      r'^yj_questions/(?P<question_type>\w+)/(?P<resource_id>\w+)/$',],
     question.question_handler.dispatch),

    ([r'^yj_exams/$',
      r'^yj_exams/(?P<resource_id>\w+)/$',],
     exam.exam_handler.dispatch),

    ([r'^yj_lessons/$',
      r'^yj_lessons/(?P<resource_id>\w+)/$',],
     lesson.lesson_handler.dispatch),


    ([r'^yj_schools/$',
      r'^yj_schools/(?P<resource_id>\w+)/$',],
     school.school_handler.dispatch),


    ([r'^yj_schooltypes/$',
      r'^yj_schooltypes/(?P<resource_id>\w+)/$',],
     schooltype.schooltype_handler.dispatch),


    ([r'^yj_school_classes/$',
      r'^yj_school_classes/(?P<resource_id>\w+)/$',],
     school_class.school_class_handler.dispatch),

    ([r'^yj_products/$',
      r'^yj_products/(?P<resource_id>\w+)/$',],
     product.product_handler.dispatch),

    ([r'^yj_teachers/$',
      r'^yj_teachers/(?P<resource_id>\w+)/$',],
     teacher.teacher_handler.dispatch),

    ([r'^yj_students/$',
      r'^yj_students/(?P<resource_id>\w+)/$',],
     student.student_handler.dispatch),

    ([r'^yj_parents/$',
      r'^yj_parents/(?P<resource_id>\w+)/$',],
     parent.parent_handler.dispatch),


    ([r'^operators/$',
      r'^operators/(?P<resource_id>\w+)/$',],
     operators.operator_handler.dispatch),

    (r'^stats/$',
      stats.handler.dispatch),

    ([r'^yj_subject_avatars/$'],
     grade_subject_textbook_knowledge.subject_avatar_handler.dispatch),

    ([r'^yj_identityauthentication/$',
      r'^yj_identityauthentication/(?P<resource_id>\w+)/$', ],
     identity_authentication.handler.dispatch),

    ([r'^yj_tasks/$',
      r'^yj_tasks/(?P<resource_id>\w+)/$', ],
     tasks.handler.dispatch),

#     (r'^qiniu/video/(?P<action>\w+)$',
#      qiniucloud.qiniu_handler.dispatch, {'resource_type': 'video'}),
#     (r'^qiniu/img/(?P<action>\w+)$',
#      qiniucloud.qiniu_handler.dispatch, {'resource_type': 'img'}),

    (r'^qiniu/$',
     qiniucloud.qiniu_handler.dispatch),

    (r'^yj_goods/$',
     goods.handler.dispatch),
    (r'^yj_account/$',
     yjaccount.handler.dispatch),
    (r'^yj_notice/$',
     notice.handler.dispatch),
    ([r'^yj_proxy/$',
      r'^yj_proxy/(?P<resource_id>\w+)/$',],
     proxy.handler.dispatch),

    (r'^yj_mgr/$',
     mgr.handler.dispatch),

    ([r'^yj_orders/$'],
     order.handler.dispatch),

    ([r'^yj_coupon/$',
      r'^yj_coupon/(?P<resource_id>\w+)/$',],
     coupon.handler.dispatch),

    (r'^loginAs$', loginout.handler.loginAs),
    (r'^loginas_step1$', loginout.handler.mgrToOtherRole_step1),

    ([r'^yj_publisher/$',
      r'^yj_publisher/(?P<resource_id>\d+)/$', ],
     publisher.handler.dispatch),

    ([r'^yj_exam_book/$',
      r'^yj_exam_book/(?P<resource_id>\w+)/$', ],
     exam_book.exam_book_handler.dispatch),

]

addPreCheck(urlpatterns_api_agrs,CheckUserIsAdminForApiCaller)


urlpatterns = [

    url(r'^login$', loginout.handler.login),
    url(r'^loginReq$', loginout.handler.loginReq),
    url(r'^logoutreq$', loginout.handler.logoutReq),
    url(r'^loginas_step2$', loginout.handler.mgrToOtherRole_step2),

] + urlpatterns_api
